package com.xw.manger;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.exp.ServiceException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Description: 阿里云管理类
 * @Author: ASUS
 * @Date: 2024/12/19 09:15
 * @Version: 1.0
 */
@Component
public class AliyunManger {


    @Value("${aliyun.region}")
    private String region;

    @Value("${aliyun.access-key}")
    private String accessKeyId;

    @Value("${aliyun.secret-key}")
    private String secretKey;

    @Value("${aliyun.point}")
    private String point;


    //读取AccessKey信息
    public DefaultAcsClient initVodClient() {
        String regionId = region;  // 点播服务接入地域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secretKey);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * 获取音/视频上传地址和凭证
     *
     * @param client 发送请求客户端
     * @return CreateUploadVideoResponse 获取音/视频上传地址和凭证响应数据
     * @throws Exception
     */
    public CreateUploadVideoResponse createUploadVideo(String title, String fileName, DefaultAcsClient client) throws Exception {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle(title);
        request.setFileName(fileName);
        return client.getAcsResponse(request);
    }


    //初始OSS客户端
    public static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }

    //上传文件
    public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, File localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        ossClient.putObject(bucketName, objectName, localFile);
    }


    public String decodeBase64(String data) {
        return new String(Base64.decodeBase64(data));
    }


    public File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        // 检查文件是否为空
        if (multipartFile.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 创建一个临时文件
        File tempFile = File.createTempFile("upload", null);

        // 将MultipartFile的内容写入到临时文件中
        try (InputStream in = multipartFile.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) {
            IoUtil.copy(in, out);
        }

        return tempFile;
    }


    // 客户端

    /**
     * 使用AK&SK初始化账号Client，需要设置AccessKeyId、AccessKeySecret
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.vod20170321.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 访问ID：必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID与其对应的值。
                .setAccessKeyId(accessKeyId)
                // 访问密保：必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET与其对应的值。
                .setAccessKeySecret(secretKey);
        // Endpoint 请参考 https://api.aliyun.com/product/vod
        config.endpoint = point;
        return new com.aliyun.vod20170321.Client(config);
    }


    public void deleteVideo(String id) {
        try {
            //初始化对象
            DefaultAcsClient client = initVodClient();
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("20001", "删除视频失败");
        }
    }
}
